class Compiler{
  constructor(vm) {
    this.vm = vm
    this.el = vm.$el
    // 为的是初始化进入页面的时候也会进行模板编译
    this.compile(this.el)
  }
  // 编译模板，处理文本节点好元素jied
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      // 判断node节点，如果node节点有子节点，则要递归调用compile方法
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  // 编译元素节点，处理指令
  compileElement(node) {
    // 遍历元素节点的所有属性
    Array.from(node.attributes).forEach(attr => {
      // 判断是否是指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        attrName = attrName.substr(2)
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update(node, key, attrName) {
    let attrs = attrName.split(':');
    let handlerName = attrs.length > 1 ? attrs[1] : null;
    let updateFn = this[attrs[0] + 'Updater']
    updateFn && updateFn.call(this, node, this.vm[key], key, handlerName)
  }

  textUpdater(node, value, key, handlerName) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }

  modelUpdater(node, value, key,handlerName ) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定，以实现视图发生改变时改变数据
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  // v-html指令
  htmlUpdater(node, value, key, handlerName) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }

  // v-on指令
  onUpdater(node, value, key, handlerName) {
    node.addEventListener(handlerName, value)
    new Watcher(this.vm, key, (newValue) => {
      node.removeEventListener(handlerName, value)
      node.addEventListener(handlerName, newValue)
    })
  }
  // 编译文本节点，处理插值表达式
  compileText(node) {
    // console.dir(node)
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      
      // 创建watcher对象，当数据改变时更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  // 判断元素属性是否是指令
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }
  // 判断节点是否是文本节点
  isTextNode(node) {
    return node.nodeType === 3
  }
  // 判断节点是否是元素节点
  isElementNode(node) {
    return node.nodeType === 1
  }
}